<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 表单搜索区 -->
      <div class="search-box">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="文章分类">
            <el-select placeholder="请选择一个分类" v-model="query.cate_id">
              <el-option
                v-for="item in cateList"
                :key="item.id"
                :label="item.cate_name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文章状态">
            <el-select placeholder="请选择状态" v-model="query.state">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="initArticle">查询</el-button>
            <el-button type="info">重置</el-button>
          </el-form-item>
        </el-form>
        <el-button type="primary" class="add-btn" @click="dialogVisible = true">添加文章</el-button>
      </div>
      <el-dialog
        title="发布文章"
        :visible.sync="dialogVisible"
        :before-close="handleClose"
        fullscreen
      >
        <!-- 添加的表单 -->
        <el-form ref="addForm" :model="addData" label-width="80px" :rules="rules">
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="addData.title" placeholder="请选择标题"></el-input>
          </el-form-item>
          <el-form-item label="选择分类" prop="cate_id">
            <el-select placeholder="请选择分类" v-model="addData.cate_id">
              <el-option
                v-for="item in cateList"
                :key="item.id"
                :label="item.cate_name"
                :value="item.id"
              ></el-option>
              <!-- <el-option label="北京" value="2"> </el-option>
              <el-option label="上海" value="0"> </el-option> -->
            </el-select>
          </el-form-item>
          <el-form-item label="文章内容">
            <quill-editor ref="myQuillEditor" v-model="addData.content"> </quill-editor>

            <!-- Or manually control the data synchronization（或手动控制数据流） -->
          </el-form-item>
          <el-form-item label="文章封面">
            <div>
              <img :src="imgUrl" alt="" v-if="imgUrl" class="cover-img" />
              <img src="@/assets/images/cover.jpg" class="cover-img" alt="" v-else />
            </div>
            <input type="file" ref="fileRef" style="display: none" @change="chooseImg" />
            <el-button type="text" @click="$refs.fileRef.click()">选择图片</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="publish('已发布')">发布</el-button>
            <el-button type="info" @click="publish('草稿')">存为草稿</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 表格区  -->
      <el-table :data="articleList" style="width: 100%" border stripe>
        <el-table-column prop="id" label="ID" width="180"> </el-table-column>
        <el-table-column prop="title" label="文章标题" width="180"> </el-table-column>
        <el-table-column prop="cate_name" label="所属分类"> </el-table-column>
        <el-table-column label="发布时间">
          <template v-slot="obj">{{ obj.row.pub_date | date_format }} </template>
        </el-table-column>
        <el-table-column prop="state" label="文章状态"> </el-table-column>
        <el-table-column label="操作"> </el-table-column>
      </el-table>
      <!-- 分页区 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="query.pagenum"
        :page-sizes="[2, 3, 4, 5]"
        :page-size="query.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import { getCateAPI } from '@/api/category'
import { addDataAPI, getArticleAPI } from '@/api/article'
import dayjs from 'dayjs'
export default {
  name: 'ArtList',
  data() {
    return {
      dialogVisible: false,
      imgUrl: '',
      total: 0,
      addData: {
        title: '',
        cate_id: '',
        content: '',
        cover_img: '',
        state: ''
      },
      query: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      articleList: [],
      cateList: [],
      rules: {
        title: [
          { required: true, message: '标题必填', trigger: 'blur' },
          { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: ['blur', 'change'] }
        ],
        cate_id: [
          { required: true, message: '必须选择一个分类', trigger: ['blur', 'change'] },
          {
            pattern: /^[1-9][0-9]*$/,
            message: '分类id必须是大于0的整数',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },
  methods: {
    handleClose() {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      this.dialogVisible = false
    },
    async initCategory() {
      const { data: res } = await getCateAPI()
      if (res.code === 0) {
        this.cateList = res.data
      } else {
        this.$message.error(res.message)
      }
    },
    chooseImg() {
      if (this.$refs.fileRef.files.length > 0) {
        this.imgUrl = URL.createObjectURL(this.$refs.fileRef.files[0])

        this.addData.cover_img = this.$refs.fileRef.files[0]
      } else {
        this.addData.cover_img = ''
        this.imgUrl = ''
      }
    },
    publish(s) {
      this.addData.state = s
      this.$refs.addForm.validate(async valid => {
        if (!valid) return
        if (this.addData.content === '') return this.$message.error('文章内容不能为空')
        if (this.addData.cover_img === '') return this.$message.error('文章封面不能为空')
        const fd = new FormData()
        for (const key in this.addData) {
          fd.append(key, this.addData[key])
        }
        const { data: res } = await addDataAPI(fd)
        if (res.code === 0) {
          this.$message.success(res.message)
          this.dialogVisible = false
          this.$refs.addForm.resetFields()
          this.addData.content = ''
          this.imgUrl = ''
        } else {
          this.$message.error(res.message)
        }
      })

      // fd.forEach((value, key) => {
      //   console.log(key, value)
      // })
    },
    async getarticle() {
      const { data: res } = await getArticleAPI(this.query)
      this.articleList = res.data
      this.total = res.total
    },
    handleSizeChange(newSize) {
      // console.log(newSize) // 得到最新的，每页 显示 newSize 条数据
      this.query.pagesize = newSize
      this.query.pagenum = 1
      // 调用获取文章的方法，重新使用新的参数发送请求，获取数据，更新页面
      this.initArticle()
    },
    // 页码改变的时候，触发的事件
    handleCurrentChange(newPage) {
      // console.log(newPage) // 表示点击的，或者跳转的最新的页码值
      this.query.pagenum = newPage
      this.initArticle()
    },
    async initArticle() {
      const { data: res } = await getArticleAPI(this.query)
      if (res.code === 0) {
        this.articleList = res.data // 把数据赋值给数据项
        this.total = res.total
      } else {
        this.$message.error(res.message)
      }
    }
  },
  created() {
    this.initCategory()
    this.getarticle()
    this.initArticle()
  },
  filters: {
    date_format(val) {
      return dayjs(val).format('YYYY-MM-DD HH:mm:ss')
    }
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}
/deep/.ql-editor {
  height: 240px;
}
.cover-img {
  height: 280px;
  width: 400px;
  object-fit: cover;
}
.add-btn {
  margin-top: 0px;
}
.el-pagination {
  margin-top: 15px;
}
</style>
